﻿using DotNetty.Transport.Bootstrapping;
using DotNetty.Transport.Channels;
using DotNetty.Transport.Channels.Sockets;
using DotNetty.Codecs.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DotNetty.Codecs.Http.WebSockets;
using DotNetty.Handlers.Timeout;

namespace WinFormsApp1.dotnetty
{
    internal class WebSocketDotNettyServer
    {
        private static WebSocketDotNettyServer server = new WebSocketDotNettyServer();
        public static WebSocketDotNettyServer Instance => server;

        private int port = 8888;
        /// <summary>
        /// 服务器是否已运行
        /// </summary>
        private bool IsServerRunning = false;
        /// <summary>
        /// 关闭侦听器事件
        /// </summary>
        private ManualResetEvent ClosingArrivedEvent = new ManualResetEvent(false);
        public void Start(int _port)
        {
            try
            {
                if (IsServerRunning)
                {
                    ClosingArrivedEvent.Set();  // 停止侦听
                }
                else
                {
                    this.port = _port;
                    //线程池任务
                    ThreadPool.QueueUserWorkItem(ThreadPoolCallback);
                }
                //var args= (new TcpServerParams()
                //{
                //    ServerIP = ServerIP,
                //    ServerPort = ServerPort,
                //    Backlog = Backlog
                //});
                //RunServerAsync(args).ConfigureAwait(false);
            }
            catch (Exception exp)
            {

            }
        }

        private void ThreadPoolCallback(object state)
        {
            RunServerAsync().Wait();
        }
        public async Task RunServerAsync()
        {
            IEventLoopGroup bossGroup = new MultithreadEventLoopGroup(1);
            IEventLoopGroup workerGroup = new MultithreadEventLoopGroup();

            try
            {
                ServerBootstrap bootstrap = new ServerBootstrap();
                bootstrap.Group(bossGroup, workerGroup)
                    .Channel<TcpServerSocketChannel>()
                    .Option(ChannelOption.SoBacklog, 1000) //设置网络IO参数等
                    .Option(ChannelOption.SoKeepalive, true)//保持连接
                    .ChildHandler(new WebSocketDotNettyInitializer());

                IChannel boundChannel = await bootstrap.BindAsync(this.port);
                //运行至此处，服务启动成功
                IsServerRunning = true;

                ClosingArrivedEvent.Reset();
                ClosingArrivedEvent.WaitOne();

                await boundChannel.CloseAsync();

            }
            finally
            {
                await Task.WhenAll(
                    bossGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)),
                    workerGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)));
            }
        }
    }
}
